import React, { Component } from 'react'
import s from './index.less'
import { Input, Row, Col, Button, Select, Form, Icon, DatePicker } from 'antd'
import moment from 'moment'
import { connect } from 'dva'
import PropTypes from 'prop-types'

const { Option } = Select
const FormItem = Form.Item
const { RangePicker } = DatePicker

const formLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
}

@connect(s => ({
  ...s['commonTable'],
}))
class Comp extends Component {
  static defaultProps = {
    option: [],
    dataSource: {},
    showLabel: false,
  }
  static propTypes = {
    option: PropTypes.arrayOf(
      PropTypes.shape({
        type: PropTypes.string.isRequired,
        alias: PropTypes.oneOfType([PropTypes.string, PropTypes.array]).isRequired,
        name: PropTypes.string
      }),
    ),
    dataSource: PropTypes.object,
    onSearch: PropTypes.func,
    showLabel: PropTypes.bool,
  }

  constructor(props) {
    super(props)
    this.state = {
      isMore: true,
    }
  }

  // componentDidMount() {}

  renderField = (alias, params) => {
    const { getFieldDecorator } = this.props.form
    return (comp) => {
      return (
        getFieldDecorator(alias, { ...params })(comp)
      )
    }
  }

  //渲染文本组件
  renderInput = (item, key) => {
    const {showLabel, tableSearch}=this.props
    const { name, alias, ...props } = item
    return (
      <Col span={6} key={key}>
        <FormItem label={showLabel && name} {...formLayout} >
          {this.renderField(alias, {
            initialValue: tableSearch[alias],
          })(
            <Input
              allowClear
              placeholder={`请输入${name}`}
              {...props}
            />,
          )}
        </FormItem>
      </Col>
    )
  }

  //渲染下拉菜单视图
  renderSelect = (item, key) => {
    const { dataSource, tableSearch, showLabel} = this.props
    const { name, alias, init, list, fieldNames = { label: 'label', value: 'value' }, ...props } = item
    const data = list || dataSource[alias] || []
    return (
      <Col span={6} key={key}>
        <FormItem label={showLabel && name} {...formLayout}>
          {this.renderField(alias, {
            initialValue: tableSearch[alias] || init,
          })(
            <Select
              allowClear
              placeholder={`请选择${name}`}
              showSearch
              optionFilterProp={'children'}
              style={{ width: '100%' }}
              {...props}
            >
              {
                data.map(v => (
                  <Option
                    key={v[fieldNames.value]}
                    value={v[fieldNames.value]}
                    title={v[fieldNames.label]}
                  >
                    {v[fieldNames.label]}
                  </Option>
                ))
              }
            </Select>,
          )}
        </FormItem>
      </Col>
    )
  }

  //渲染单个日期
  renderTime = (item, key) => {
    const {showLabel, tableSearch}=this.props
    const { name, init, alias, format = 'YYYY-MM-DD', ...props } = item
    let initVal = null
    if (init) {
      initVal = moment(init)
    } else {
      if (tableSearch[alias]) {
        initVal = moment(tableSearch[alias])
      }
    }
    return (
      <Col span={6} key={key}>
        <FormItem label={showLabel && name} {...formLayout}>
          {this.renderField(alias, {
            initialValue: initVal
          })(
            <DatePicker
              placeholder={`请选择${name}`}
              style={{ width: '100%' }}
              format={format}
              {...props}
            />,
          )}
        </FormItem>
      </Col>
    )
  }

  //渲染日期范围选择
  renderTimeRange = (item, key) => {
    const {showLabel}=this.props
    const { name, placeholder=['开始日期', '结束日期'], format = 'YYYY-MM-DD', alias, ...props } = item
    return (
      <Col span={6} key={key}>
        <FormItem label={showLabel && name} {...formLayout}>
          {this.renderField(`${alias[0]}${alias[1]}`)(
            <RangePicker
              showTime={false}
              style={{ width: '100%' }}
              format={format}
              placeholder={placeholder}
              {...props}
            />,
          )}
        </FormItem>
      </Col>
    )
  }

  // //渲染级联效果
  // renderCascader = (item, index) => {
  //   const { name, alias, fieldNames, showLabel } = item
  //   const { dataSource } = this.props
  //   const data = dataSource[alias] || []
  //   return (
  //     <Col span={6} key={index}>
  //       <FormItem label={showLabel&&name} {...formLayout}>
  //         {
  //           this.renderField(alias)(
  //             <Cascader
  //               allowClear
  //               placeholder={`请选择${name}`}
  //               options={data}
  //               fieldNames={fieldNames}
  //             />,
  //           )
  //         }
  //       </FormItem>
  //     </Col>
  //   )
  // }

  //渲染列表数据
  renderDataList = (option) => {
    return option.map((item, index) => {
      switch (item.type) {
        case 'input':
          return this.renderInput(item, index)
        case 'time':
          return this.renderTime(item, index)
        case 'select':
          return this.renderSelect(item, index)
        case 'time-range':
          return this.renderTimeRange(item, index)
        // case 'cascader':
        //   return this.renderCascader(item, index)
        default:
          return null
      }
    })
  }

  //展开更多被点击
  onIsMoreDown = () => {
    this.setState({ isMore: !this.state.isMore })
  }


  //表单提交按钮被按下
  onFormSubmit = (e) => {
    e.preventDefault()
    const { form, onSearch, option } = this.props
    form.validateFields((err, val) => {
      if (!err) {
        let times = {}
        option.forEach(v => {
          const { alias, type, format = 'YYYY-MM-DD' } = v
          if (type === 'time-range') {
            let valArr = val[`${alias[0]}${alias[1]}`]
            if (valArr && valArr.length) {
              times = {
                [alias[0]]: moment(valArr[0]).format(format),
                [alias[1]]: moment(valArr[1]).format(format),
              }
            } else {
              times = {
                [alias[0]]: undefined,
                [alias[1]]: undefined,
              }
            }
            delete val[`${alias[0]}${alias[1]}`]
          }
          if (type === 'time') {
            let valTime = val[alias]
            if (valTime) {
              times[alias] = moment(valTime).format(format)
            }
          }
        })
        onSearch && onSearch({
          ...val,
          ...times,
        })
      }
    })
  }

  //重置被按下
  // onReset = () => {
  //   const {form, onReset} = this.props
  //   form.resetFields()
  //   onReset && onReset()
  // }

  renderBtns = () => {
    const { isMore } = this.state
    const { option } = this.props
    return (
      <div className={s.moreBtn}>
        <Button type={'primary'} htmlType="submit">搜索</Button>
        {/*<Button htmlType="button" onClick={this.onReset}>重置</Button>*/}
        {option.length <= 4
          ? null
          : <div onClick={this.onIsMoreDown} className={'blue'} style={{ cursor: 'pointer' }}>
            {isMore ? <span>收起<Icon type="up"/></span> : <span>展开<Icon type="down"/></span>}
          </div>}
      </div>

    )
  }

  render() {
    const { option } = this.props
    const { isMore } = this.state
    return (
      <Form className={`${s['form']} jx-search-form`} onSubmit={this.onFormSubmit}>
        <Row className={s['form-row']}>
          {isMore
            ? this.renderDataList(option)
            : this.renderDataList(option.slice(0, 4))
          }
          {option.length <= 3 && this.renderBtns()}
        </Row>
        {option.length > 3 && this.renderBtns()}
      </Form>
    )
  }
}

export default Form.create()(Comp)
